import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { toast } from 'sonner';
import {
  Users,
  MessageSquare,
  Rocket,
  Activity as ActivityIcon,
  RefreshCw,
  Bell,
  Settings,
  TrendingUp,
  TrendingDown,
  Cpu,
  HardDrive,
  Wifi,
  CheckCircle,
  AlertTriangle,
  Clock,
  BarChart3,
  UserPlus,
  FileText,
  Database,
  Plus,
  Grid3X3,
  Layout,
  ArrowUpRight,
  ArrowDownRight,
  AlertCircle,
  Server,
  Shield,
  Download,
  Search
} from 'lucide-react';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
} from '@dnd-kit/sortable';
import { DashboardWidget, WidgetData, WidgetType } from '@/components/dashboard/DashboardWidget';

// 小部件类型定义扩展
type ExtendedWidgetType = WidgetType | 'system-monitor';
import { SystemMonitor } from '@/components/SystemMonitor';
import { NotificationCenter, type Notification, type Activity } from '@/components/NotificationCenter';
import { PersonalizationSettings } from '@/components/PersonalizationSettings';
import { DataExport } from '@/components/DataExport';
import { AdvancedSearch } from '@/components/AdvancedSearch';

// 小部件数据接口
interface DashboardWidgetData {
  id: string;
  type: ExtendedWidgetType;
  title: string;
  size: 'small' | 'medium' | 'large';
  data: any;
  position: number;
  isVisible: boolean;
}
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';

// 数据类型定义
interface DashboardStats {
  title: string;
  value: string;
  change: string;
  trend: 'up' | 'down';
  icon: React.ComponentType<any>;
  color: string;
  loading?: boolean;
}

interface SystemHealth {
  cpu: number;
  memory: number;
  disk: number;
  network: 'healthy' | 'warning' | 'error';
  database: 'online' | 'offline' | 'maintenance';
  services: {
    name: string;
    status: 'running' | 'stopped' | 'error';
    uptime: string;
  }[];
}

interface DashboardActivity {
  id: string;
  type: 'user' | 'system' | 'release' | 'chat';
  title: string;
  description: string;
  timestamp: string;
  status: 'success' | 'warning' | 'error' | 'info';
}

interface QuickAction {
  title: string;
  description: string;
  icon: React.ComponentType<any>;
  color: string;
  route: string;
  enabled: boolean;
}

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [stats, setStats] = useState<DashboardStats[]>([]);
  const [systemHealth, setSystemHealth] = useState<SystemHealth | null>(null);
  const [recentActivities, setRecentActivities] = useState<DashboardActivity[]>([]);
  const [notifications, setNotifications] = useState<number>(0);
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date());
  
  // 小部件配置状态
  const [widgets, setWidgets] = useState<DashboardWidgetData[]>([]);
  const [isAddWidgetOpen, setIsAddWidgetOpen] = useState(false);
  const [isLayoutMode, setIsLayoutMode] = useState(false);
  const [newWidgetType, setNewWidgetType] = useState<ExtendedWidgetType>('stats');
  const [newWidgetTitle, setNewWidgetTitle] = useState('');
  const [newWidgetSize, setNewWidgetSize] = useState<'small' | 'medium' | 'large'>('medium');
  const [isNotificationOpen, setIsNotificationOpen] = useState(false);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const [isExportOpen, setIsExportOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  
  // 拖拽传感器配置
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // 快速操作配置
  const quickActions: QuickAction[] = [
    {
      title: '用户管理',
      description: '管理系统用户',
      icon: Users,
      color: 'bg-blue-500',
      route: '/users',
      enabled: true
    },
    {
      title: '智能对话',
      description: '查看对话记录',
      icon: MessageSquare,
      color: 'bg-green-500',
      route: '/chat',
      enabled: true
    },
    {
      title: '版本发布',
      description: '管理版本发布',
      icon: Rocket,
      color: 'bg-purple-500',
      route: '/release-management',
      enabled: true
    },
    {
      title: '数据分析',
      description: '查看分析报告',
      icon: BarChart3,
      color: 'bg-orange-500',
      route: '/analytics',
      enabled: true
    }
  ];

  // 模拟最近活动数据
  const recentActivitiesData: DashboardActivity[] = [
    {
      id: '1',
      type: 'release',
      title: '版本 v2.1.3 发布成功',
      description: '新增智能聊天优化功能',
      timestamp: '2分钟前',
      status: 'success'
    },
    {
      id: '2',
      type: 'chat',
      title: '智能对话峰值预警',
      description: '当前并发对话数超过阈值',
      timestamp: '15分钟前',
      status: 'warning'
    },
    {
      id: '3',
      type: 'user',
      title: '新用户注册激增',
      description: '今日新增用户数达到月度峰值',
      timestamp: '1小时前',
      status: 'info'
    },
    {
      id: '4',
      type: 'system',
      title: '系统维护完成',
      description: '数据库优化和性能提升已完成',
      timestamp: '3小时前',
      status: 'success'
    }
  ];

  /**
   * 获取仪表盘统计数据
   * @returns Promise<DashboardStats[]> 统计数据数组
   */
  const fetchDashboardStats = async (): Promise<DashboardStats[]> => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      return [
        {
          title: '总用户数',
          value: Math.floor(Math.random() * 10000 + 10000).toLocaleString(),
          change: `+${(Math.random() * 20).toFixed(1)}%`,
          trend: 'up',
          icon: Users,
          color: 'text-blue-600'
        },
        {
          title: '智能对话',
          value: Math.floor(Math.random() * 5000 + 5000).toLocaleString(),
          change: `+${(Math.random() * 15).toFixed(1)}%`,
          trend: 'up',
          icon: MessageSquare,
          color: 'text-green-600'
        },
        {
          title: '版本发布',
          value: Math.floor(Math.random() * 100 + 100).toString(),
          change: `+${(Math.random() * 25).toFixed(1)}%`,
          trend: 'up',
          icon: Rocket,
          color: 'text-purple-600'
        },
        {
          title: '系统活跃度',
          value: `${(Math.random() * 10 + 85).toFixed(1)}%`,
          change: Math.random() > 0.5 ? `+${(Math.random() * 5).toFixed(1)}%` : `-${(Math.random() * 3).toFixed(1)}%`,
          trend: Math.random() > 0.5 ? 'up' : 'down',
          icon: ActivityIcon,
          color: 'text-orange-600'
        }
      ];
    } catch (error) {
      console.error('获取统计数据失败:', error);
      toast.error('获取统计数据失败');
      return [];
    }
  };

  /**
   * 获取系统健康状态
   * @returns Promise<SystemHealth> 系统健康状态数据
   */
  const fetchSystemHealth = async (): Promise<SystemHealth> => {
    try {
      await new Promise(resolve => setTimeout(resolve, 800));
      
      return {
        cpu: Math.floor(Math.random() * 40 + 30),
        memory: Math.floor(Math.random() * 30 + 50),
        disk: Math.floor(Math.random() * 20 + 60),
        network: Math.random() > 0.8 ? 'warning' : 'healthy',
        database: Math.random() > 0.9 ? 'maintenance' : 'online',
        services: [
          {
            name: 'Web服务器',
            status: Math.random() > 0.95 ? 'error' : 'running',
            uptime: `${Math.floor(Math.random() * 30 + 1)}天`
          },
          {
            name: 'API服务',
            status: 'running',
            uptime: `${Math.floor(Math.random() * 15 + 5)}天`
          },
          {
            name: '数据库',
            status: Math.random() > 0.98 ? 'stopped' : 'running',
            uptime: `${Math.floor(Math.random() * 45 + 10)}天`
          }
        ]
      };
    } catch (error) {
      console.error('获取系统健康状态失败:', error);
      toast.error('获取系统健康状态失败');
      throw error;
    }
  };

  /**
   * 获取最近活动数据
   * @returns Promise<DashboardActivity[]> 最近活动数组
   */
  const fetchRecentActivities = async (): Promise<DashboardActivity[]> => {
    try {
      await new Promise(resolve => setTimeout(resolve, 600));
      return recentActivitiesData;
    } catch (error) {
      console.error('获取最近活动失败:', error);
      return [];
    }
  };

  /**
   * 刷新所有数据
   */
  const refreshData = useCallback(async () => {
    setRefreshing(true);
    try {
      const [statsData, healthData, activitiesData] = await Promise.all([
        fetchDashboardStats(),
        fetchSystemHealth(),
        fetchRecentActivities()
      ]);
      
      setStats(statsData);
      setSystemHealth(healthData);
      setRecentActivities(activitiesData);
      setLastUpdated(new Date());
      setNotifications(Math.floor(Math.random() * 5));
      
      toast.success('数据已更新');
    } catch (error) {
      toast.error('数据更新失败');
    } finally {
      setRefreshing(false);
    }
  }, []);

  /**
   * 拖拽结束处理函数
   */
  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event;
    
    if (over && active.id !== over.id) {
      setWidgets((items) => {
        const oldIndex = items.findIndex((item) => item.id === active.id);
        const newIndex = items.findIndex((item) => item.id === over.id);
        
        return arrayMove(items, oldIndex, newIndex);
      });
      
      toast.success('小部件位置已更新');
    }
  }, []);

  /**
   * 添加小部件函数
   */
  const handleAddWidget = useCallback(() => {
    if (!newWidgetTitle.trim()) {
      toast.error('请输入小部件标题');
      return;
    }
    
    const newWidget: WidgetData = {
      id: `widget-${Date.now()}`,
      type: newWidgetType,
      title: newWidgetTitle,
      size: newWidgetSize,
      data: generateWidgetData(newWidgetType),
      position: { x: 0, y: 0 },
      isVisible: true
    };
    
    setWidgets(prev => [...prev, newWidget]);
    setIsAddWidgetOpen(false);
    setNewWidgetTitle('');
    setNewWidgetType('stats');
    setNewWidgetSize('medium');
    
    toast.success('小部件已添加');
  }, [newWidgetTitle, newWidgetType, newWidgetSize]);

  /**
   * 删除小部件函数
   */
  const handleRemoveWidget = useCallback((widgetId: string) => {
    setWidgets(prev => prev.filter(widget => widget.id !== widgetId));
    toast.success('小部件已删除');
  }, []);

  /**
   * 编辑小部件函数
   */
  const handleEditWidget = useCallback((widget: any) => {
    console.log('编辑小部件:', widget);
    // 这里可以打开编辑对话框
    toast.info('小部件编辑功能开发中');
  }, []);

  /**
   * 切换小部件显示状态
   */
  const handleToggleWidget = useCallback((widgetId: string, isVisible: boolean) => {
    setWidgets(prev => prev.map(widget => 
      widget.id === widgetId ? { ...widget, isVisible } : widget
    ));
    toast.success(isVisible ? '小部件已显示' : '小部件已隐藏');
  }, []);

  /**
   * 生成小部件数据函数
   */
  const generateWidgetData = useCallback((type: ExtendedWidgetType) => {
    switch (type) {
      case 'stats':
        return stats;
      case 'chart':
        return {
          labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
          datasets: [{
            label: '用户增长',
            data: [65, 59, 80, 81, 56, 55],
            borderColor: 'rgb(75, 192, 192)',
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
          }]
        };
      case 'progress':
        return systemHealth;
      case 'activity':
        return recentActivities;
      case 'system':
        return systemHealth;
      case 'quick-actions':
        return quickActions;
      case 'system-monitor':
        return {
          // 系统监控组件会自己获取数据，这里只需要空对象
        };
      default:
        return null;
    }
  }, [stats, systemHealth, recentActivities, quickActions]);

  /**
   * 处理快速操作点击
   * @param action 快速操作配置
   */
  const handleQuickAction = (action: QuickAction) => {
    if (!action.enabled) {
      toast.warning('该功能暂未开放');
      return;
    }
    navigate(action.route);
  };

  /**
   * 处理新建任务
   */
  const handleCreateTask = () => {
    // 这里可以打开新建任务对话框或跳转到任务页面
    console.log('创建新任务');
    // 示例：跳转到任务管理页面
    // navigate('/tasks/new');
  };

  /**
   * 处理通知点击
   */
  const handleNotificationClick = (notification: Notification) => {
    console.log('通知点击:', notification);
    // 如果通知有关联的URL，可以进行跳转
    if (notification.actionUrl) {
      navigate(notification.actionUrl);
    }
    setIsNotificationOpen(false);
  };

  /**
   * 处理活动点击
   */
  const handleActivityClick = (activity: Activity) => {
    console.log('活动点击:', activity);
    // 根据活动类型进行相应的处理
    switch (activity.type) {
      case 'user_login':
      case 'user_logout':
        navigate('/users');
        break;
      case 'file_upload':
        navigate('/files');
        break;
      case 'report_generated':
        navigate('/analytics');
        break;
      case 'system_update':
      case 'error_occurred':
        navigate('/settings');
        break;
    }
    setIsNotificationOpen(false);
  };

  // 初始化数据加载
  useEffect(() => {
    const loadInitialData = async () => {
      setLoading(true);
      try {
        await refreshData();
      } finally {
        setLoading(false);
      }
    };
    
    loadInitialData();
  }, [refreshData]);

  // 处理点击外部区域关闭通知中心
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (isNotificationOpen && !target.closest('.notification-center-container')) {
        setIsNotificationOpen(false);
      }
    };

    if (isNotificationOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isNotificationOpen]);

  // 设置自动刷新
  useEffect(() => {
    const interval = setInterval(() => {
      if (!refreshing) {
        refreshData();
      }
    }, 30000); // 每30秒自动刷新

    return () => clearInterval(interval);
  }, [refreshing, refreshData]);
  
  // 初始化默认小部件
  useEffect(() => {
    if (widgets.length === 0 && stats.length > 0) {
      const defaultWidgets: DashboardWidgetData[] = [
        {
          id: 'widget-stats',
          type: 'stats',
          title: '数据概览',
          size: 'large',
          data: stats,
          position: 0,
          isVisible: true
        },
        {
          id: 'widget-system-monitor',
          type: 'system-monitor',
          title: '系统监控',
          size: 'large',
          data: {},
          position: 1,
          isVisible: true
        },
        {
          id: 'widget-activity',
          type: 'activity',
          title: '最近活动',
          size: 'medium',
          data: recentActivities,
          position: 2,
          isVisible: true
        },
        {
          id: 'widget-quick-actions',
          type: 'quick-actions',
          title: '快速操作',
          size: 'small',
          data: quickActions,
          position: 3,
          isVisible: true
        }
      ];
      
      setWidgets(defaultWidgets);
    }
  }, [stats.length, widgets.length]);

  // 移除了可能导致无限循环的 updateWidgetData 函数
  // 现在数据生成逻辑已移至 DashboardWidget 组件内部

  /**
   * 获取状态颜色
   * @param status 状态字符串
   * @returns 对应的CSS类名
   */
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success': return 'text-green-600';
      case 'warning': return 'text-yellow-600';
      case 'error': return 'text-red-600';
      case 'info': return 'text-blue-600';
      default: return 'text-gray-600';
    }
  };

  /**
   * 获取服务状态颜色
   * @param status 服务状态
   * @returns 对应的CSS类名
   */
  const getServiceStatusColor = (status: string) => {
    switch (status) {
      case 'running': return 'bg-green-500';
      case 'stopped': return 'bg-red-500';
      case 'error': return 'bg-red-500';
      default: return 'bg-gray-500';
    }
  };

  /**
   * 获取状态图标
   * @param status 状态字符串
   * @returns React组件
   */
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'success':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'warning':
        return <AlertCircle className="w-4 h-4 text-yellow-500" />;
      case 'info':
        return <ActivityIcon className="w-4 h-4 text-blue-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };

  /**
   * 获取状态徽章样式
   * @param status 状态字符串
   * @returns CSS类名
   */
  const getStatusBadge = (status: string) => {
    const variants = {
      success: 'bg-green-100 text-green-800',
      warning: 'bg-yellow-100 text-yellow-800',
      info: 'bg-blue-100 text-blue-800',
      default: 'bg-gray-100 text-gray-800'
    };
    return variants[status as keyof typeof variants] || variants.default;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex items-center space-x-2">
          <RefreshCw className="h-6 w-6 animate-spin" />
          <span>加载中...</span>
        </div>
      </div>
    );
  }

  const isLoading = loading;

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 页面标题和操作栏 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">控制台概览</h1>
            <p className="text-gray-600 mt-1">
              企业级后台管理系统数据总览 • 最后更新: {lastUpdated.toLocaleTimeString()}
            </p>
          </div>
          <div className="flex items-center space-x-3">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsSearchOpen(true)}
            >
              <Search className="w-4 h-4 mr-2" />
              高级搜索
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsLayoutMode(!isLayoutMode)}
            >
              <Layout className="w-4 h-4 mr-2" />
              {isLayoutMode ? '退出编辑' : '编辑布局'}
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsSettingsOpen(true)}
            >
              <Settings className="w-4 h-4 mr-2" />
              个性化设置
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsExportOpen(true)}
            >
              <Download className="w-4 h-4 mr-2" />
              导出数据
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsAddWidgetOpen(true)}
            >
              <Plus className="w-4 h-4 mr-2" />
              添加小部件
            </Button>
            <div className="relative notification-center-container">
              <Button 
                variant="outline" 
                size="sm"
                onClick={() => setIsNotificationOpen(!isNotificationOpen)}
              >
                <Bell className="w-4 h-4 mr-2" />
                通知 {notifications > 0 && `(${notifications})`}
              </Button>
              {isNotificationOpen && (
                <div className="absolute right-0 top-full mt-2 z-50">
                  <NotificationCenter
                    onNotificationClick={handleNotificationClick}
                    onActivityClick={handleActivityClick}
                    maxItems={10}
                  />
                </div>
              )}
            </div>
            <Button 
              variant="outline" 
              size="sm"
              onClick={refreshData}
              disabled={refreshing}
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
              {refreshing ? '刷新中...' : '实时刷新'}
            </Button>
            <Button size="sm" onClick={handleCreateTask}>
              <Plus className="w-4 h-4 mr-2" />
              新建任务
            </Button>
          </div>
        </div>

        {/* 可拖拽的小部件布局 */}
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext
            items={widgets.filter(w => w.isVisible).map(w => w.id)}
            strategy={rectSortingStrategy}
          >
            <div className={`grid gap-4 ${isLayoutMode ? 'border-2 border-dashed border-primary/50 p-4 rounded-lg' : ''}`}>
              {widgets.filter(w => w.isVisible).map((widget) => {
                return (
                  <DashboardWidget
                    key={widget.id}
                    widget={widget}
                    isLayoutMode={isLayoutMode}
                    onEdit={handleEditWidget}
                    onRemove={handleRemoveWidget}
                    onToggle={handleToggleWidget}
                    onNavigate={navigate}
                  />
                );
              })}
            </div>
          </SortableContext>
        </DndContext>

        {/* 添加小部件对话框 */}
        <Dialog open={isAddWidgetOpen} onOpenChange={setIsAddWidgetOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>添加新小部件</DialogTitle>
              <DialogDescription>
                选择要添加的小部件类型和配置
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="widget-title">小部件标题</Label>
                <Input
                  id="widget-title"
                  value={newWidgetTitle}
                  onChange={(e) => setNewWidgetTitle(e.target.value)}
                  placeholder="输入小部件标题"
                />
              </div>
              <div>
                <Label htmlFor="widget-type">小部件类型</Label>
                <Select value={newWidgetType} onValueChange={(value: WidgetType) => setNewWidgetType(value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择小部件类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="stats">数据统计</SelectItem>
                    <SelectItem value="chart">图表</SelectItem>
                    <SelectItem value="progress">进度条</SelectItem>
                    <SelectItem value="activity">活动记录</SelectItem>
                    <SelectItem value="system">系统状态</SelectItem>
                    <SelectItem value="quick-actions">快速操作</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="widget-size">小部件大小</Label>
                <Select value={newWidgetSize} onValueChange={(value: 'small' | 'medium' | 'large') => setNewWidgetSize(value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择小部件大小" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="small">小</SelectItem>
                    <SelectItem value="medium">中</SelectItem>
                    <SelectItem value="large">大</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsAddWidgetOpen(false)}>
                取消
              </Button>
              <Button onClick={handleAddWidget}>
                添加小部件
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 布局模式提示 */}
        {isLayoutMode && (
          <Card className="border-primary/50 bg-primary/5">
            <CardContent className="pt-6">
              <div className="flex items-center space-x-2 text-primary">
                <Grid3X3 className="w-5 h-5" />
                <span className="font-medium">布局编辑模式</span>
                <span className="text-sm text-muted-foreground">拖拽小部件重新排列，点击删除按钮移除小部件</span>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 个性化设置对话框 */}
        <PersonalizationSettings
          isOpen={isSettingsOpen}
          onClose={() => setIsSettingsOpen(false)}
          widgets={widgets}
          onWidgetsChange={setWidgets}
        />

        {/* 数据导出对话框 */}
        <DataExport
          isOpen={isExportOpen}
          onClose={() => setIsExportOpen(false)}
          dashboardData={{
            stats,
            systemHealth,
            recentActivities,
            widgets,
            lastUpdated
          }}
        />
        
        {/* 高级搜索对话框 */}
        <AdvancedSearch
          isOpen={isSearchOpen}
          onClose={() => setIsSearchOpen(false)}
        />
      </div>
    </div>
  );
};

export default Dashboard;